import 'dart:async';
import 'dart:math';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/singleton/constant_repository/constant_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bean/bg_terminal_music_list_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/bg_sys_recommend_music_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_column_response_bean.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_image_desc_widget.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_batch_setting_page.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_set_category_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_set_column_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_image_set_style_dialog.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_service.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_publish_view_model.dart';
import 'package:e_reception_flutter/ui/smart_home/publish/smart_home_store_details_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:flutter/material.dart';
import 'package:keyboard_utils/keyboard_listener.dart';
import 'package:keyboard_utils/keyboard_utils.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';
import '../../app_main.dart';
import '../smart_home_category_response_bean.dart';
import '../smart_home_set_image_category_dialog.dart';
import '../smart_home_set_image_style_dialog.dart';
import '../smart_home_style_type_bean.dart';
import '../smart_home_upload_service.dart';


/// 发图片选择上传类型
class SmartHomePublishImageSingleUploadPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "SmartHomePublishImageSingleUploadPage";
  final String shid;
  final String sfid;
  final List<SmartHomeUploadItemBean> currentList;
  final String router;

  const SmartHomePublishImageSingleUploadPage({Key key, this.sfid, this.shid, this.currentList, this.router})
      : super(key: key);

  @override
  SmartHomePublishImageSingleUploadPageState createState() => SmartHomePublishImageSingleUploadPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context, String shid,
      List<SmartHomeUploadItemBean> currentList, {String sfid, String router}) {
    return RouterUtils.routeForFutureResult(
      context,
      SmartHomePublishImageSingleUploadPage(
        sfid:sfid,
        shid:shid,
        currentList:currentList,
        router:router,
      ),
      routeName: SmartHomePublishImageSingleUploadPage.ROUTER,
    );
  }
}

class SmartHomePublishImageSingleUploadPageState
    extends BaseState<SmartHomePublishImageSingleUploadPage>
    with
        AutomaticKeepAliveClientMixin,
        NavigatorPageMixin {

  ///获取state
  static SmartHomePublishImageSingleUploadPageState of(BuildContext context) {
    final SmartHomePublishImageSingleUploadPageState result =
    context.findAncestorStateOfType<SmartHomePublishImageSingleUploadPageState>();
    return result;
  }
  bool isAliveConfirm = true;

  List<SmartHomeUploadItemBean> _imageList = List();

  //栏目
  final List<ColumnListBean> _columnList = List();
  //空间
  final List<SpatialTypeListBean> _categoryList = List();
  //风格
  final List<SmartHomeStyleTypeBean> _styleList = List();

  SmartHomePublishViewModel _viewModel;
  List<MusicListBean> _musicList = List();
  BgSysRecommendMusicViewModel _musicViewModel;

  KeyboardUtils _keyboardUtils = KeyboardUtils();
  @override
  void initState() {
    _keyboardUtils.add(listener: KeyboardListener(
      willHideKeyboard: (){
        FocusManager.instance.primaryFocus?.unfocus();
      },
      willShowKeyboard: (height){}
    ));
    super.initState();
    _viewModel = new SmartHomePublishViewModel(this);
    _musicViewModel = new BgSysRecommendMusicViewModel(this, "");
    _imageList.addAll(widget?.currentList);
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _musicViewModel.getBgByHsn(context, "", (musicList) async {
        _musicList.addAll(musicList);
        setRandomMusicId();
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return LightAnnotatedRegion(
      child: Scaffold(
        backgroundColor: Colors.white,
        body: _toMainColumnWidget(),
      ),
    );
  }

  void setRandomMusicId(){
    if(_musicList.isEmpty){
      return;
    }
    if(_imageList.isEmpty){
      return;
    }
    _imageList.forEach((element) {
      element.sysmid = getRandomMusicId();
    });
  }

  String getRandomMusicId(){
    if(_musicList.isEmpty){
      return "";
    }
    int index = Random().nextInt(_musicList.length);
    return _musicList.elementAt(index).id;
  }
  /// 函数节流
  ///
  /// [func]: 要执行的方法
  Function throttle(
      Future Function() func,
      ) {
    if (func == null) {
      return func;
    }
    bool enable = true;
    Function target = () {
      if (enable == true) {
        enable = false;
        func().then((_) {
          enable = true;
        });
      }
    };
    return target;
  }
  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        _toSettingWidget(),
        _toListWidget(),
        // Expanded(
        //   child: _toMainPlaceHolderWidget(),
        // )
      ],
    );
  }


  Widget _toTopBarWidget() {
    final double statusHeight = ScreenUtils.getStatusBarH(context);
    return Container(
      height: 44 + statusHeight,
      color: Color(0XFFF2F3F4),
      padding: EdgeInsets.only(top: statusHeight),
      child: Row(
        children: <Widget>[
          ClickAnimateWidget(
            child: Container(
              width: 40,
              height: 44,
              alignment: Alignment.centerLeft,
              padding: const EdgeInsets.only(left: 15.6),
              child: Image.asset(
                "images/top_bar_back_ico.png",
                width: 9,
              ),
            ),
            scale: 1.4,
            onClick: () {
              FocusScope.of(context).requestFocus(FocusNode());
              Navigator.of(context).maybePop();
            },
          ),
          Text(
            "独立上传",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                fontSize: 17,
                height: 1.22,
                fontWeight: FontWeight.w600),
          ),
          Spacer(),
          _toSaveWidget(),
        ],
      ),
    );
  }

  Widget _toSaveWidget() {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        SmartHomePublishService service = SmartHomePublishService().setList(
          context,
          widget?.shid,
          "",
          "",
          "",
          _imageList,
          0,
          widget?.sfid ?? "",
          "",
        );
        if (service != null) {
          VgHudUtils.show(context, "正在发布");
          if ((_imageList?.length ?? 0) > 0) {
            //多图上传
            service.singleUpload(VgBaseCallback(onSuccess: (val) {
              VgHudUtils.hide(context);
              VgToastUtils.toast(AppMain.context, "上传完成");
              RouterUtils.popUntil(
                  context, widget?.router ?? SmartHomeStoreDetailsPage.ROUTER);
            }, onError: (msg) {
              VgHudUtils.hide(context);
              VgToastUtils.toast(AppMain.context, "上传失败");
              RouterUtils.popUntil(
                  context, widget?.router ?? SmartHomeStoreDetailsPage.ROUTER);
            }));
          }
        }
        // _upload();
      },
      child: Container(
        width: 48,
        height: 24,
        margin: EdgeInsets.only(right: 15),
        decoration: BoxDecoration(
          color: isAliveConfirm?ThemeRepository.getInstance().getPrimaryColor_1890FF():Color(0xFFCFD4DB),
          borderRadius: BorderRadius.circular(12),
        ),
        alignment: Alignment.center,
        child: Text(
          "发布",
          style: TextStyle(
              color: Colors.white, fontSize: 12, fontWeight: FontWeight.w500),
        ),
      ),
    );
  }

  Widget _toSettingWidget(){
    return Container(
      height: 45,
      padding: EdgeInsets.symmetric(horizontal: 12),
      alignment: Alignment.center,
      child: Row(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: ()async{
              List<SmartHomeUploadItemBean> imageList = await SmartHomePublishImageBatchSettingPage.navigatorPush(context,
                  widget?.shid, _imageList);
              if(imageList != null){
                setState(() {
                  _imageList.clear();
                  _imageList.addAll(imageList);
                });
              }
            },
            child: Container(
              child: Row(
                children: [
                  Image.asset(
                    "images/icon_package_setting.png",
                    width: 14.5,
                  ),
                  SizedBox(width: 6.5,),
                  Text(
                    "批量设置",
                    style: TextStyle(
                      fontSize: 12,
                      color: Color(0XFF8B93A5),
                    ),
                  ),
                ],
              ),
            ),
          ),
          Spacer(),
          Text(
            "共${_imageList.length}文件",
            style: TextStyle(
              fontSize: 12,
              color: Color(0XFF8B93A5),
            ),
          ),
        ],
      ),
    );
  }

  Widget _toListWidget(){
    return Expanded(
      child: ScrollConfiguration(
          behavior: MyBehavior(),
          child: ListView.separated(
              padding: EdgeInsets.only(
                  left: 12,
                  right: 12,
                  bottom: getNavHeightDistance(context)),
              itemCount: _imageList?.length ?? 0,
              physics: BouncingScrollPhysics(),
              shrinkWrap: true,
              itemBuilder: (BuildContext context, int index) {
                return _toListItemWidget(context, index, _imageList?.elementAt(index));
              },
              separatorBuilder: (BuildContext context, int index) {
                return SizedBox(height: 24,);
              }
          )),
    );
  }

  Widget _toListItemWidget(BuildContext context, int index, SmartHomeUploadItemBean itemBean) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(4),
          child: VgCacheNetWorkImage(
            itemBean?.getPicOrVideoUrl() ?? "",
            width: 80,
            height: 80,
            imageQualityType: ImageQualityType.middleDown,
          ),
        ),
        SizedBox(width: 8,),
        Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            _toSelectColumnTypeStyleWidget(itemBean),
            SizedBox(height: 8,),
            SmartHomeImageDescWidget(itemBean: itemBean,),
          ],
        ),
      ],
    );
  }

  Widget _toSelectColumnTypeStyleWidget(SmartHomeUploadItemBean itemBean){
    return Container(
      width: ScreenUtils.screenW(context) - 112,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _toSelectColumnWidget(itemBean),
          _toSelectCategoryWidget(itemBean),
          _toSelectStyleWidget(itemBean),
        ],
      ),
    );
  }

  ///选择类别
  Widget _toSelectColumnWidget(SmartHomeUploadItemBean itemBean){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_columnList.isNotEmpty){
          SmartHomePublishImageSetColumnDialog.navigatorPushDialog(context,
              itemBean?.scid,
              _columnList, (columnListBean){
                setState(() {
                  itemBean?.scid = columnListBean?.scid;
                  itemBean?.scidName = columnListBean?.name;
                });
              });
        }else{
          _viewModel.getLatestColumn(widget?.shid, (columnList){
            _columnList.addAll(columnList);
            SmartHomePublishImageSetColumnDialog.navigatorPushDialog(context,
                itemBean?.scid,
                _columnList, (columnListBean){
                  setState(() {
                    itemBean?.scid = columnListBean?.scid;
                    itemBean?.scidName = columnListBean?.name;
                  });
                });
          });
        }

      },
      child: Container(
        height: 26,
        width: 83,
        padding: EdgeInsets.symmetric(horizontal: 8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          color: Colors.white,
          border: Border.all(
              color: Color(0XFFB0B3BF),
              width: 0.2
          ),
        ),
        child: Row(
          children: [
            Text(
              StringUtils.isNotEmpty(itemBean?.scidName)?itemBean?.scidName:"类别",
              style: TextStyle(
                  fontSize: 13,
                  color: StringUtils.isNotEmpty(itemBean?.scidName)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFFB0B3BF)
              ),
            ),
            Spacer(),
            Image.asset(
              "images/icon_arrow_down_black.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }

  ///选择空间
  Widget _toSelectCategoryWidget(SmartHomeUploadItemBean itemBean){
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_categoryList.isNotEmpty){
          SmartHomePublishImageSetCategoryDialog.navigatorPushDialog(context,
              itemBean?.stid,
              _categoryList, (categoryListBean){
                setState(() {
                  itemBean?.stid = categoryListBean?.stid;
                  itemBean?.stidName = categoryListBean?.name;
                });
              });
        }else{
          _viewModel.getLatestCategory(widget?.shid, (categoryList){
            _categoryList.addAll(categoryList);
            SmartHomePublishImageSetCategoryDialog.navigatorPushDialog(context,
                itemBean?.stid,
                _categoryList, (categoryListBean){
                  setState(() {
                    itemBean?.stid = categoryListBean?.stid;
                    itemBean?.stidName = categoryListBean?.name;
                  });
                });
          });
        }
      },
      child: Container(
        height: 26,
        width: 83,
        padding: EdgeInsets.symmetric(horizontal: 8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          color: Colors.white,
          border: Border.all(
              color: Color(0XFFB0B3BF),
              width: 0.2
          ),
        ),
        child: Row(
          children: [
            Text(
              StringUtils.isNotEmpty(itemBean?.stidName)?itemBean?.stidName:"空间",
              style: TextStyle(
                  fontSize: 13,
                  color: StringUtils.isNotEmpty(itemBean?.stidName)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFFB0B3BF)
              ),
            ),
            Spacer(),
            Image.asset(
              "images/icon_arrow_down_black.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }

  ///选择风格
  Widget _toSelectStyleWidget(SmartHomeUploadItemBean itemBean){
    String style = itemBean?.getStyleName();
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: (){
        if(_styleList.isNotEmpty){
          SmartHomePublishImageSetStyleDialog.navigatorPushDialog(context,
              itemBean?.style,
              _styleList, (styleBean){
                setState(() {
                  itemBean?.style = styleBean?.style;
                  itemBean?.styleName = styleBean?.name;
                });
              });
        }else{
          _viewModel.getLatestStyle(widget?.shid, (styleList){
            _styleList.addAll(styleList);
            SmartHomePublishImageSetStyleDialog.navigatorPushDialog(context,
                itemBean?.style,
                _styleList, (styleBean){
                  setState(() {
                    itemBean?.style = styleBean?.style;
                    itemBean?.styleName = styleBean?.name;
                  });
                });
          });
        }
      },
      child: Container(
        height: 26,
        width: 83,
        padding: EdgeInsets.symmetric(horizontal: 8),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          color: Colors.white,
          border: Border.all(
              color: Color(0XFFB0B3BF),
              width: 0.2
          ),
        ),
        child: Row(
          children: [
            Text(
              StringUtils.isNotEmpty(style)?style:"风格",
              style: TextStyle(
                  fontSize: 13,
                  color: StringUtils.isNotEmpty(style)?ThemeRepository.getInstance().getCardBgColor_21263C():Color(0XFFB0B3BF)
              ),
            ),
            Spacer(),
            Image.asset(
              "images/icon_arrow_down_black.png",
              width: 6,
            )
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
